package Agency.models;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import javax.swing.JOptionPane;
import Agency.views.*;


/**
 *
 * @author wangari
 */
public class NewTenantModel extends javax.swing.JFrame {
    
    Connection conn = null;
    public AddTenantView myNewTenant;
    private ActionListener actionlistener;
    
    public NewTenantModel(){
       myNewTenant = new  AddTenantView();
       //myNewTenant.setVisible(true);
    }
    /**
     * clearing all the TextFields after saving the data
     */
    public void clearAllTextFields(){
    myNewTenant.getTenantName().setText(null);
     myNewTenant.getTenantIdNo().setText(null);
       myNewTenant.getTenantPhoneNum().setText(null);
        myNewTenant.getTenantOccupation().setText(null);
         myNewTenant.getHousePlotNum().setText(null);
    }
    /**
     * A method to add a new tenant. the tenant information is entered, names and the house they have taken
     * and the information is saved in a database.
     */
    public void AddNewTennant(){
        String tenantsName= myNewTenant.getTenantName().getText();
        String tenantsIdNo= myNewTenant.getTenantIdNo().getText();
        String tenantsPhoneNumber = myNewTenant.getTenantPhoneNum().getText();
        String houseType =myNewTenant.getTenantHseType().getSelectedItem().toString();
        String tenantstown = myNewTenant.getTenantTown().getSelectedItem().toString();
        String tenantsGender = myNewTenant.getTenantGender().getSelectedItem().toString();
        String tenantsOccupation = myNewTenant.getTenantOccupation().getText();
        String hsePlotNum = myNewTenant.getHousePlotNum().getText();
        
  try{
       Class.forName("com.mysql.jdbc.Driver").newInstance();
 conn = java.sql.DriverManager.getConnection(
 "jdbc:mysql://localhost/MusyiAgency?user=root&password=");
 
 PreparedStatement p=conn.prepareStatement("INSERT INTO  TenantsInformation(TenantsName,TenantsIdNo,TenantsPhoneNumber,HouseType,HousePlotNum,Town,Gender,Occupation)Values(?,?,?,?,?,?,?,?)");
            
    p.setString(1, tenantsName);
    p.setString(2, tenantsIdNo);
    p.setString(3,tenantsPhoneNumber);
    p.setString(4,houseType);
    p.setString(5,hsePlotNum);
    p.setString(6, tenantstown);          
    p.setString(7, tenantsGender);        
    p.setString(8, tenantsOccupation);
   
    p.execute(); 
    JOptionPane.showMessageDialog(null,"Tenant saved successfully");
    clearAllTextFields();
    p.close();
   
    }catch(Exception e){
        System.out.println("Error"+e.toString());
              
    }
 }
    /**
     * Method to close the add tenant view, it first clears all the text fields and then closes
     */
    public void closeView(){
        clearAllTextFields();
    myNewTenant.setVisible(false);    
    }
    
    
}
